import 'package:flutter/material.dart';
import 'package:color_block_downloader_flutter/config/app_config.dart';
import 'package:color_block_downloader_flutter/utils/color_utils.dart';
import 'package:color_block_downloader_flutter/utils/file_utils.dart';
import 'package:color_block_downloader_flutter/utils/image_utils.dart';

/// 控制面板
class ControlPanel extends StatefulWidget {
  const ControlPanel({super.key});

  @override
  State<ControlPanel> createState() => _ControlPanelState();
}

class _ControlPanelState extends State<ControlPanel> {
  final _formKey = GlobalKey<FormState>();
  final _colorController = TextEditingController();
  final _widthController = TextEditingController();
  final _heightController = TextEditingController();
  final _filenameController = TextEditingController();

  String _selectedFormat = 'PNG';
  String? _saveDirectory;

  @override
  void initState() {
    super.initState();
    _colorController.text = ColorUtils.colorToHex(AppConfig.defaultColor);
    _widthController.text = '1920';
    _heightController.text = '1080';
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 颜色输入
            TextFormField(
              controller: _colorController,
              decoration: const InputDecoration(
                labelText: '颜色 (HEX)',
                hintText: '#RRGGBB',
              ),
              validator: (value) {
                if (value == null || !ColorUtils.validateHexColor(value)) {
                  return '请输入有效的16进制颜色值';
                }
                return null;
              },
            ),
            const SizedBox(height: 16),
            // 尺寸输入
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _widthController,
                    decoration: const InputDecoration(labelText: '宽度'),
                    keyboardType: TextInputType.number,
                    validator: (value) {
                      if (value == null || int.tryParse(value) == null) {
                        return '请输入有效的宽度';
                      }
                      return null;
                    },
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: TextFormField(
                    controller: _heightController,
                    decoration: const InputDecoration(labelText: '高度'),
                    keyboardType: TextInputType.number,
                    validator: (value) {
                      if (value == null || int.tryParse(value) == null) {
                        return '请输入有效的高度';
                      }
                      return null;
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            // 格式选择
            DropdownButtonFormField<String>(
              value: _selectedFormat,
              decoration: const InputDecoration(labelText: '格式'),
              items: <String>['PNG', 'JPG', 'BMP']
                  .map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  })
                  .toList(),
              onChanged: (String? newValue) {
                setState(() {
                  _selectedFormat = newValue!;
                });
              },
            ),
            const SizedBox(height: 16),
            // 自定义文件名
            TextFormField(
              controller: _filenameController,
              decoration: const InputDecoration(labelText: '自定义文件名 (可选)'),
            ),
            const SizedBox(height: 16),
            // 保存目录
            Row(
              children: [
                Expanded(child: Text(_saveDirectory ?? '未选择保存目录')),
                ElevatedButton(
                  onPressed: () async {
                    String? directory = await FileUtils.selectSaveDirectory();
                    if (directory != null) {
                      setState(() {
                        _saveDirectory = directory;
                      });
                    }
                  },
                  child: const Text('选择目录'),
                ),
              ],
            ),
            const SizedBox(height: 16),
            // 下载和打开目录按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                ElevatedButton(
                  onPressed: () {
                    if (_saveDirectory != null) {
                      FileUtils.openDirectory(_saveDirectory!);
                    }
                  },
                  child: const Text('打开目录'),
                ),
                const SizedBox(width: 16),
                ElevatedButton(
                  onPressed: () async {
                    if (_formKey.currentState!.validate()) {
                      final color = ColorUtils.hexToColor(
                        _colorController.text,
                      );
                      final width = int.parse(_widthController.text);
                      final height = int.parse(_heightController.text);
                      final format = _selectedFormat;
                      final filename = _filenameController.text;
                      final imageData = await ImageUtils.createImage(
                        color,
                        width,
                        height,
                        format,
                      );

                      if (imageData != null) {
                        final result = await FileUtils.saveFile(
                          imageData,
                          _saveDirectory,
                          filename,
                          format,
                        );

                        if (result != null) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text('图片已保存到 $result')),
                          );
                        } else {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('保存图片失败')),
                          );
                        }
                      } else {
                        ScaffoldMessenger.of(
                          context,
                        ).showSnackBar(const SnackBar(content: Text('生成图片失败')));
                      }
                    }
                  },
                  child: const Text('下载'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
